//
//  LiuHomeViewModel.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/3/30.
//  Copyright © 2017年 刘晓晨. All rights reserved.
//

import UIKit
import SDWebImage
class LiuHomeViewModel: NSObject {
    
    var homeStatuses:[LiustatuseViewModel] = [LiustatuseViewModel]()
    
    var tipContent:String?
    
    
    func loadHomeData(isPullup: Bool, callBack:@escaping (Bool)->()){
        
        //上拉加载
        var maxId:Int64 = 0
        //下载刷新
        var sinceId:Int64 = 0
        
        if isPullup {
            //下拉
            print("上拉")
            maxId = homeStatuses.last?.homeStatuse?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        } else {
            //上拉
            print("下拉")
            sinceId = homeStatuses.first?.homeStatuse?.id ?? 0
    
        }
        
        
        //根据token获取数据
        if let userAccount = LiuUserAccountViewModel.sharedUserAccountViewModel.userAccount {
            
            LiuNetworkManager.sharedTools.requestHomeData(sinceId:sinceId, maxId:maxId, userAccount: userAccount, compeleteCallBack: { (response, error) in
                if error != nil {
                    print("首页数据获取失败:error",error!)
                    callBack(false)
                    return
                }
                
                guard let dic = response as? [String: Any] else {
                    print("首页数据格式有异常")
                    callBack(false)
                    return
                }
                //代码执行到此说明首页数据获取成功
                let tempArray = dic["statuses"] as! [[String:Any]]
                let dataArray = NSArray.yy_modelArray(with: LiuStatus.self, json: tempArray) as! [LiuStatus]
                
                //创建一个可变的数组
                var array:[LiustatuseViewModel] = [LiustatuseViewModel]()
                
                //创建调度组,用于处理只有单张图片的情况
                let group = DispatchGroup()
                //遍历数组,套viewModel
                for statuse in dataArray {
                    let viewModel = LiustatuseViewModel()
                    viewModel.homeStatuse = statuse
                    array.append(viewModel)
                    
                    //判断只有一张图片的情况
                    if statuse.pic_urls?.count == 1 {
                        //原创只有一张图片的情况
                        
                        //获取图片url
                        let url = statuse.pic_urls?.first?.thumbnail_pic
                        
                        //加入调度组
                        group.enter()
                        
                        //下载图片
                        SDWebImageManager.shared().loadImage(with: URL(string:url!), options: [], progress: nil, completed: { (image, data, error, _, _, _) in
                            
                            //下载完成后从调度组中移除
                            group.leave()
                        })
                    }
                    
                    if statuse.retweeted_status?.pic_urls?.count == 1 {
                        //转发图片只有一张的情况
                        
                        //获取图片url
                        let url = statuse.retweeted_status?.pic_urls?.first?.thumbnail_pic
                        
                        //加入调度组
                        group.enter()
                        
                        //下载图片
                        SDWebImageManager.shared().loadImage(with: URL(string:url!), options: [], progress: nil, completed: { (image, data, error, _, _, _) in
                            
                            //下载完成后从调度组中移除
                            group.leave()
                        })
                    }
                    
                }

                //给属性赋值
                if isPullup {
                    //  上拉加载, 追加了加载的更多的微博数据
                    self.homeStatuses.append(contentsOf: array)
                } else {
                    //  下拉刷新, 需要把请求回来的数据插入的第一个元素的位置
                    self.homeStatuses.insert(contentsOf: array, at: 0)
                    
                    //判断下拉刷新数据的个数
                    if array.count > 0 {
                        self.tipContent = "更新了\(array.count)条微博"
                    } else {
                        self.tipContent = "没有数据了"
                    }
                }
                
                //调度组执行完毕后刷新数据
                group.notify(queue: DispatchQueue.main, execute: { 
                    callBack(true)
                })
                
            })
            
        }
   
    }
    
    
}



